<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>websocket.js</title>
</head>
<body id="box">
<div id="myPosition" draggable="true"
     style="width:10px;height:10px;border:solid 2px #F00;position: absolute;top: 0;left: 0;background-color: red;cursor: pointer;z-index: 99999;"></div>

<form id="from">
    账号:<input type="text" name="accountName" value="liaoxiang"> <br>
    密码:<input type="text" name="password" value="123456"> <br>
    <input type="button" value="登录" id="btn">
</form>

<div id="app">ioGamewebsocket.js</div>
<div id="input">
    <h2>Input</h2>
    Cmd:<input type="number" id="cmdCode" name="cmdCode" value="1"> <br>
    SubCmd:<input type="number" id="subCmdCode" name="subCmdCode" value="1"> <br>
    <textarea id="inputText" style="margin-top:20px;border: 1px #ddd solid;
   height: 150px;width: 830px; overflow-y: auto;"></textarea>
    <input type="button" value="发送" id="sendBtn">
</div>

<h2>Output</h2>
<div id="output" style="margin-top:20px;border: 1px #ddd solid; height: 260px; overflow-y: auto;">
</div>




<script type="text/javascript" th:src="@{/jquery-1.11.3.min.js}"></script>
<script type="text/javascript" th:src="@{/day.min.js}"></script>
<script type="text/javascript" th:src="@{/websocket.js}"></script>
<script>
    $(document).keydown(function (event) {
        var keyNum = event.which;  //获取键值
        var Item = $('#myPosition');  //要移动的元素
        switch (keyNum) { //判断按键
            case 37:
                Item.animate({left: '-=5px'}, 0);
                break;
            case 38:
                Item.animate({top: '-=5px'}, 0);
                break;
            case 39:
                Item.animate({left: '+=5px'}, 0);
                break;
            case 40:
                Item.animate({top: '+=5px'}, 0);
                break;
            default:
                break;
        }
    });


    $("#btn").click(function () {
        $.ajax({
            async: false,  //异步
            url: "/auth/loginAjax", //地址
            type: "post",  //请求方式
            dataType: "json",  // 返回类型
            data: $("#from").serialize(),//直接序列化form表单
            success: function (data) {
                console.log(data) //后台返回结果
                if (data.code === 0) {
                    loginSuccess(data.body.token, data.body.userId);
                } else {
                    alert(data.message);
                }
            }
        })
    })

    $("#sendBtn").click(function () {
        var cmdCode = document.getElementById("cmdCode").value;
        var subCmdCode = document.getElementById("subCmdCode").value;
        var inputText = document.getElementById("inputText").value;

        console.log("cmd:" + cmdCode + "  sunCmd:" + subCmdCode + "   data:" + inputText)
        if (inputText === undefined || inputText === "") {
            alert("内容为空");
        } else {
            sendMsgByInput(cmdCode, subCmdCode, inputText);
        }
    })

    function startAsyncSendPosition() {
        setInterval(() => {
            var divOffset = $('#myPosition').offset();
            var y = divOffset.top;
            var x = divOffset.left;

            var positionJson = {};
            positionJson.y = y;
            positionJson.x = x;

            let inputText = JSON.stringify(positionJson);
            console.log("MyPosition:" + inputText)
            sendMsgByInput(2, 1, inputText);
        }, 100);
    }

    function nearUserRefresh(bizDataJson) {
        console.log(JSON.stringify(bizDataJson))
        if (bizDataJson.code !== 0) {
            console.log("获取附近用户信息code!=0")
            return;
        }

        let userItemList = $("[id^='userItem_']");

        // 选展示出需要展示的用户位置
        let inPositionUserId = [];
        let nearPlayerInfoList = bizDataJson.body.nearPlayerInfoList;
        for (let i = 0; i < nearPlayerInfoList.length; i++) {
            let nearPlayer = nearPlayerInfoList[i];
            let userId = nearPlayer.userId;
            let x = nearPlayer.x;
            let y = nearPlayer.y;
            try {
                refreshUser(userId, x, y);
            } catch (error) {
            }
            // 放入附近的人
            inPositionUserId.push("userItem_" + userId);
        }
        // 删除已经超出范围，没返回的位置
        try {
            userItemList.each(function () {
                let thisUserId = $(this).attr("id");
                // 没有该元素，移除
                if(inPositionUserId.indexOf(thisUserId) === -1){
                    $(this).remove();
                }
            })
        } catch (error) {
        }
    }

    function refreshUser(userId, x, y) {
        if ($('#userItem_' + userId).length) {
            // 元素存在，刷新
            $('#userItem_' + userId).css("transform", "translate(" + x + "px, " + y + "px)");
        } else {
            // 元素不存在，添加
            addNewUserPlayer(userId, x, y);
        }
    }

    function addNewUserPlayer(userId, x, y) {
        $('#box').append('<div id="userItem_' + userId +
            '" style="width:10px;height:10px;border:solid 2px #0F0;position: absolute;top:0;left:0;"></div>');
    }
</script>
</body>
</html>